
import axios from 'axios'
import { GDMAP_KEY_WEB } from '@/api/config'

let map = null
if (window.AMap) { // 已载入高德地图API，则直接初始化地图
  map = new AMap.Map('container', {})
}

export const getPosition = (success, failure) => {
  if (map) {
    map.plugin('AMap.Geolocation', function () {
      const geolocation = new AMap.Geolocation({
        enableHighAccuracy: false, // 是否使用高精度定位，默认:true
        timeout: 10000         // 超过10秒后停止定位，默认：无穷大
      })
      map.addControl(geolocation)
      geolocation.getCurrentPosition()
      AMap.event.addListener(geolocation, 'complete', (data) => {
        success(data.position.getLng(), data.position.getLat())
      })
      AMap.event.addListener(geolocation, 'error', () => {
        failure('定位失败')
        console.error('定位失败')
      })
    })
  }
}

export const getDistance = (position1, position2) => {
  if (map) {
    if (!(position1 instanceof Array) || !(position2 instanceof Array)) {
      console.error('amap: position必须是数组')
      return
    }
    if (position1.length !== 2 || position2.length !== 2) {
      console.error('amap: position1长度不为2')
      return
    }
    const lnglat = new AMap.LngLat(position1[0], position1[1])
    return lnglat.distance(position2)
  }
}

export const distanceStr = (distance) => {
  if (map) {
    if (distance < 200) {
      return '200米以内'
    } else if (distance < 1000) {
      return '1Km范围以内'
    } else if (distance < 2 * 1000) {
      return '2Km范围以内'
    } else if (distance < 200 * 1000) {
      return '距离' + (distance / 1000).toFixed(1) + 'Km'
    } else {
      return '超过200Km'
    }
  }
}

export const getNearby = ({ position, keywords }, success, failure) => {
  if (map) {
    axios({
      method: 'GET',
      url: 'http://restapi.amap.com/v3/place/around',
      params: {
        key: GDMAP_KEY_WEB,
        location: position.join(','),
        keywords: keywords,
        types: '100000|110000|150000|050000|190000'
      }
    }).then((res) => {
      /* eslint-disable */
      if (res.data.status == 1) {
        if (success) {
          success(res.data.pois)
        }
      } else {
        if (failure) {
          failure(res.data.info)
        }
      }
    }).catch(e => {
      if (failure) {
        failure('获取附近人失败')
      }
      /* eslint-enable */
      console.error('获取附近人失败。详细信息：' + e.message)
    })
  }
}
